package com.mallcloud.mall.auth.handler;

import com.mallcloud.mall.admin.api.dto.SysLogDTO;
import com.mallcloud.mall.admin.api.feign.RemoteLogService;
import com.mallcloud.mall.common.core.constant.CommonConstants;
import com.mallcloud.mall.common.core.constant.SecurityConstants;
import com.mallcloud.mall.common.core.util.KeyStrResolver;
import com.mallcloud.mall.common.core.util.WebUtils;
import com.mallcloud.mall.common.log.util.SysLogUtils;
import com.mallcloud.mall.common.security.handler.AuthenticationSuccessHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录成功日志记录
 */
@Slf4j
@Component
@AllArgsConstructor
public class MallAuthenticationSuccessLogEventHandler implements AuthenticationSuccessHandler {

	private final RemoteLogService logService;

	private final KeyStrResolver tenantKeyStrResolver;

	/**
	 * 处理登录成功方法
	 * <p>
	 * 获取到登录的authentication 对象
	 * @param authentication 登录对象
	 * @param request 请求
	 * @param response 返回
	 */
	@Async
	@Override
	public void handle(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
		if (!request.getRequestURI().contains(SecurityConstants.OAUTH_TOKEN_URL)) {
			return;
		}

		String username = authentication.getName();
		SysLogDTO sysLog = SysLogUtils.getSysLog(request, username);
		sysLog.setTitle(username + "用户登录");

		Object startTimeStr = request.getAttribute(CommonConstants.REQUEST_START_TIME);
		if (Objects.nonNull(startTimeStr)) {
			Long startTime = (Long) startTimeStr;
			Long endTime = System.currentTimeMillis();
			sysLog.setTime(endTime - startTime);
		}

		String header = request.getHeader(HttpHeaders.AUTHORIZATION);
		sysLog.setServiceId(WebUtils.extractClientId(header).orElse("N/A"));
		sysLog.setTenantId(Long.parseLong(tenantKeyStrResolver.key()));

//		logService.saveLog(sysLog, SecurityConstants.FROM_IN);
		log.info("用户：{} 登录成功", username);
	}

}
